package com.hy.ai.service.impl;

import com.hy.ai.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.model.Media;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeType;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@Service
public class ChatServiceImpl  implements ChatService {

    private final ChatClient chatClient;

    public ChatServiceImpl(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public Flux<String> textChat(String prompt,String chatId){
        return chatClient.prompt()
                .user(prompt)
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)) //设置会话id
                .stream() //流式输出
                // .call() //阻塞式输出
                .content();
    }

    @Override
    public Flux<String> multiModelChat(String prompt, String chatId, List<MultipartFile> files) {
        //解析多媒体
        List<Media> mediaList = files.stream().map(file -> new Media(MimeType.valueOf(file.getContentType())
                , file.getResource())).toList();
        //请求模型
        return chatClient.prompt()
                .user(p->p.text(prompt).media(mediaList.toArray(Media[]::new)))
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)) //设置会话id
                .stream() //流式输出
                // .call() //阻塞式输出
                .content();
    }
}
